var url_ = require('../utils/url.js');
var njzxw = {
  page: null,
  /**
   * 日期加减
   */
  addDate: function (date, days){
    var d = new Date(date);
    d.setDate(d.getDate() + days);
    var m = d.getMonth() + 1;
    return d.getFullYear() + '-' + m + '-' + d.getDate(); 
  },
  /**
   * 获取配置变量数据信息
   * @param name变量名称
   * @param isOne 是否取第一条
   * @num 循环等待次数 可能还未加载好数据
   */
  getCfgVal:function(name,isOne,num){
    var cfg = wx.getStorageSync("cfg");
    console.log('===1==:',cfg=='');
    if (cfg == '' && cfg == undefined){
      num = num == undefined?0:num;
      num ++;
      if(num >= 200){
        return '';
      }
      return njzxw.getCfgVal(name, isOne, num);
    }
    if(isOne == true){
      var obj = cfg[name];
      if(obj != undefined ){
        if(obj.length > 0){
          return obj[0].value;
        }
      }
      return "";
    }else{
      return cfg[name];
    }
  },
  /**
   * 读取基本配置信息
   */
  initCfg:function(fun){
    /**
     * 加载字典表数据信息
     */
    njzxw.ajax({
      url: url_.cfgInfo,
      data:{
        weixinxcx:1
      },
      fun:function(a, b) {
        console.log('配置信息：', b);
        if(a){
          if(b.data.state == 1){
            wx.setStorageSync('cfg', b.data.data);
          }
        }
      }
    });
  },
  /**
   * 对象拷贝
   */
  extend: function (form, obj) {
    Object.assign(form, obj);
  },
  replaceAll:function(str,reg,s) {
    if (str != null)
      str = str.replace(reg, s)
    return str;
  },
  /**
   * 过滤emoji
   */
  emoji:function(str){
    return str.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "*");
  },
  /**
   * 前缀补0
   */
  zeroize: function (value, length) {
    if (!length) {
      length = 2;
    }
    value = new String(value);
    for (var i = 0, zeros = ''; i < (length - value.length); i++) {
      zeros += '0';
    }
    return zeros + value;
  },
  /*   
  函数：格式化日期   
  参数：pattern-格式化字符串   
  d：将日显示为不带前导零的数字，如1   
  dd：将日显示为带前导零的数字，如01   
  ddd：将日显示为缩写形式，如Sun   
  dddd：将日显示为全名，如Sunday   
  M：将月份显示为不带前导零的数字，如一月显示为1   
  MM：将月份显示为带前导零的数字，如01  
  MMM：将月份显示为缩写形式，如Jan  
  MMMM：将月份显示为完整月份名，如January  
  yy：以两位数字格式显示年份  
  yyyy：以四位数字格式显示年份  
  h：使用12小时制将小时显示为不带前导零的数字，注意||的用法  
  hh：使用12小时制将小时显示为带前导零的数字  
  H：使用24小时制将小时显示为不带前导零的数字  
  HH：使用24小时制将小时显示为带前导零的数字  
  m：将分钟显示为不带前导零的数字  
  mm：将分钟显示为带前导零的数字  
  s：将秒显示为不带前导零的数字  
  ss：将秒显示为带前导零的数字  
  l：将毫秒显示为不带前导零的数字  
  ll：将毫秒显示为带前导零的数字  
  tt：显示am/pm  
  TT：显示AM/PM  
  返回：格式化后的日期  
  */
  format: function (date, pattern){
    /*  
    函数：填充0字符  
    参数：value-需要填充的字符串, length-总长度  
    返回：填充后的字符串  
    */
    var zeroize = function (value, length) {
      if (!length) {
        length = 2;
      }
      value = new String(value);
      for (var i = 0, zeros = ''; i < (length - value.length); i++) {
        zeros += '0';
      }
      return zeros + value;
    };
    return pattern.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|M{1,4}|yy(?:yy)?|([hHmstT])\1?|[lLZ])\b/g, function ($0) {
      switch ($0) {
        case 'd': return date.getDate();
        case 'dd': return zeroize(date.getDate());
        case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][date.getDay()];
        case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
        case 'M': return date.getMonth() + 1;
        case 'MM': 
          var mm = zeroize(date.getMonth() + 1);
          console.log('......');
          return mm;
        case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()];
        case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][date.getMonth()];
        case 'yy': return new String(date.getFullYear()).substr(2);
        case 'yyyy': return date.getFullYear();
        case 'h': return date.getHours() % 12 || 12;
        case 'hh': return zeroize(date.getHours() % 12 || 12);
        case 'H': return date.getHours();
        case 'HH': return zeroize(date.getHours());
        case 'm': return date.getMinutes();
        case 'mm': return zeroize(date.getMinutes());
        case 's': return date.getSeconds();
        case 'ss': return zeroize(date.getSeconds());
        case 'l': return date.getMilliseconds();
        case 'll': return zeroize(date.getMilliseconds());
        case 'tt': return date.getHours() < 12 ? 'am' : 'pm';
        case 'TT': return date.getHours() < 12 ? 'AM' : 'PM';
      }
    });
  },
  login: function (fun) {
    // 登录
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          njzxw.ajax({
            url: url_.login,
            data: {
              code: res.code
            },
            isToken: false,
            fun: function (a, b) {
              if (a) {
                if (b.data.state == 1) {
                  wx.setStorageSync("token", b.data.token);
                  wx.setStorageSync("isBdMobile", b.data.isBdMobile);
                  if (typeof fun == 'function') {
                    fun();
                  }
                } else {
                  // wx.showModal({
                  //   title: '系统提示',
                  //   content: '认证出现异常'
                  // })
                }
              } else {
                // wx.showModal({
                //   title: '系统提示',
                //   content: '认证出现异常'
                // })
              }
            }
          });
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
  /**
   * 生成uuid
   */
  guid: function () {
    return (njzxw.S4() + njzxw.S4() + "-" + njzxw.S4() + "-" + njzxw.S4() + "-" + njzxw.S4() + "-" + njzxw.S4() + njzxw.S4() + njzxw.S4());
  },
  S4: function () {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  },
  ajax: function (opt) {
    var def = {
      url: '',
      data: {},
      isToken: true,
      load: false,
      loadTitle: '加载中...',
      fun: function (a, b) {

      }
    };
    njzxw.extend(def, opt);
    console.log('def.load == true:', def.load == true);
    if (def.load == true) {
      wx.showLoading({
        title: def.loadTitle,
        mask: true
      })
    }

    def.success = function (res) {
      console.log("请求值：", def, "请求返回值", res);
      
      if (res.statusCode == 510) {
        njzxw.login(function () {
          njzxw.ajax(def);
        });
        return;
      } else if (res.statusCode == 404){
        def.fun(false, res);
        return;
      }
      if (res.data.msg == '服务器出现错误，请稍后再试'){
        def.fun(false, res);
        return;
      }
      def.fun(true, res);
    }
    def.fail = function (res) {
      console.log("请求值：", def, "请求返回值", res);
      if (res.statusCode == 510) {
        njzxw.login(function () {
          njzxw.ajax(def);
        });
        return;
      }
      wx.showModal({
        title: '系统提示',
        content: '访问出现错误'
      });
    }
    def.method = 'POST';
    def.dataType = 'json';

    def.data['requset_type'] = '小程序访问';
    if (def.isToken != false) {
      def.data['token'] = wx.getStorageSync("token");
      // console.log('token:::' + def.data['token']);
      if (njzxw.isEmpty(def.data['token'])) {
        // wx.showModal({
        //   title: '系统提示',
        //   content: '您未登录，或登录已失效',
        // });
        njzxw.login(function () {
          // console.log('???????????????????????????????');
          njzxw.ajax(def);
        });
        return;
      }
    }
    // console.log('??????????1?????????????????????');

    wx.request(def);
  },
  /**
   * 开始加载列表
   */
  loadStart: function (page) {
    page.setData({
      end_hide: null,
      null_show: false,
      list: [],
      pageNum: 0
    });
  },
  /**
     * 加载列表数据
     */
  loadData: function (page, url, data,dataFun) {
    // console.log('=-=-=:', njzxw.isStart(page));
    if (!page.data.hasOwnProperty('list')) {
      page.setData({
        list: []
      });
    }
    if (njzxw.isStart(page)) {
      var $this = page;
      var pageNum = page.data.pageNum + 1;
      data['pageNum'] = pageNum;
      njzxw.ajax({
        url: url,
        data: data,
        load:true,
        fun: function (a, b) {
          if (a) {
            console.log(b);
            if (b.data.state == 1) {
              var ddd = b.data.data;
              if (typeof dataFun =='function'){
                ddd = dataFun(ddd);
              }
              console.log('====',ddd);
              $this.setData({
                list: $this.data.list.concat(ddd),
                pageNum: pageNum
              });
              njzxw.isEnd($this, b.data);
            } else {
              njzxw.alert({
                msg: b.data.msg
              });
            }
          } else {
            njzxw.alert({
              msg: b.data.msg
            });
          }
          wx.hideLoading();
        }
      });
    }
  },
  /**
   * 是否能加载
   */
  isStart: function (page) {
    console.log('======', page.data.end_hide, !page.data.hasOwnProperty('end_hide') || page.data.end_hide == true || page.data.end_hide == null);
    if (!page.data.hasOwnProperty('end_hide') || page.data.end_hide == true || page.data.end_hide == null) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      return true;
    }
    return false;
  },
  /**
   * 是否结束加载
   */
  isEnd: function (page, data) {
    wx.stopPullDownRefresh();
    wx.hideLoading();
    console.log('page.data.list.length:', page.data.list.length, data.total);
    if (page.data.list.length >= data.total) {
      page.data.end_hide = false;
      if (data.total == 0) {
        page.setData({
          null_show: true
        });
      } else {
        page.setData({
          end_hide: false
        });
      }
    }
  },
  /**
   * 初始化基本函数
   */
  initFun: function (page) {
    njzxw.page = page;
    page['redirectTo'] = this.redirectTo;
    page['navigateTo'] = this.navigateTo;
    page['switchTab'] = this.switchTab;
    page['blur_'] = this.blur_;
  },
  blur_: function (e) {
    var reg = njzxw.getDataVal(e, 'reg');
    var val = e.detail.value;
    var msg = njzxw.getDataVal(e, 'msg');
    var name = njzxw.getDataVal(e, 'name');
    var fun = njzxw.getDataVal(e, 'fun');
    var isEmpty = njzxw.isEmpty(val);

    console.log('new RegExp(reg).test(val):', new RegExp(reg).test(val), val, reg);
    if (!isEmpty && !new RegExp(reg).test(val)) {
      njzxw.alert({
        msg: msg
      });
      val = '';
    }

    var fromData = njzxw.page.data['fromData'];
    if (fromData == undefined) {
      fromData = {};
    }
    fromData[name] = val;
    njzxw.page.setData({
      'fromData': fromData
    });
    if (!njzxw.isEmpty(fun)) {
      njzxw.page[fun](njzxw.page, fromData);
    }
  },
  getFromVal: function (page, name) {
    if (page.data['fromData'] == undefined) {
      return "";
    }
    if (page.data['fromData'][name] == undefined) {
      return "";
    }
    return page.data['fromData'][name];
  },
  trim: function (obj) {
    return (obj == null || obj == undefined) ? '' : obj.replace(/(^\s*)|(\s*$)/g, "")
  },
  isEmpty: function (obj) {
    console.log('obj:', typeof obj);
    if (typeof obj == 'number') {
      if (obj == undefined || obj == null) {
        return true;
      } else {
        return false;
      }
    }
    if (typeof obj == 'object') {
      return false;
    }
    if (this.trim(obj) == '') {
      return true;
    }
    return false;
  },
  /**
   * 获取定义的data-xx 值
   */
  getDataVal: function (e, name) {
    return e.currentTarget.dataset[name];
  },
  redirectTo: function (e) {
    var url = e.currentTarget.dataset.url;
    if (!njzxw.isEmpty(url)) {
      wx.redirectTo({
        url: url
      })
    }
  },
  navigateTo: function (e) {
    var url = e.currentTarget.dataset.url;
    if (!njzxw.isEmpty(url)) {
      wx.navigateTo({
        url: url
      })
    }
  },
  switchTab: function (e) {
    var url = e.currentTarget.dataset.url;
    if (!njzxw.isEmpty(url)) {
      wx.switchTab({
        url: url
      })
    }
  },
  /**
   * 检查是否有存在用户信息
   */
  checkUserInfo:function(page,fun){
    page.setData({
      alert_: {
        show: true
      }
    });
    var dat = wx.getStorageSync('userInfo');
    if (dat == undefined || dat == '') {
      njzxw.alert({
        title:'',
        page: page,
        btn: ['过会授权', '现在授权'],
        msg: '我们请求获取您的头像与名称信息来作为您的基本信息，是否现在授权？',
        confirm: true,
        original: false,
        type: "getUserInfo",
        fun: function (a, b) {
          if (b != undefined) {
            //将获取的用户信息存储到用户中心中
            njzxw.ajax({
              url: url_.saveInfo,
              data:{
                data:{
                  nick_name:b.nickName,
                  avatarUrl: b.avatarUrl,
                  country: b.country,
                  city: b.city,
                  province: b.province,
                  sex: b.gender
                }
              },
              fun:function(a,x){
                if(a){
                  if(x.data.state == 1){
                    wx.setStorageSync("userInfo", b);
                    if (typeof fun == 'function') {
                      fun(b);
                    }
                  }else{
                    njzxw.alert({msg:x.data.msg});
                  }
                }else{
                  njzxw.alert({
                    msg: '无法获取您的信息，请至用户中心重新点击头像获取'
                  });
                }
                wx.hideLoading();
              }
            });

            if(typeof fun == 'function'){
              fun(b);
            }
          } else {
            wx.hideLoading();
            njzxw.alert({
              msg: '无法获取您的信息，请至用户中心重新点击头像获取'
            });
            return;
          }
        }
      });
    }else{
      if(typeof fun == 'function'){
        fun(dat);
      }
    }
  },
  /**
   * 校验登录信息
   */
  checkReg: function (page) {
    page.setData({
      alert_: {
        show: true
      }
    });
    if (wx.getStorageSync('isBdMobile') == '0') {

      njzxw.alert({
        page: page,
        btn: ['过会绑定', '现在绑定'],
        msg: '您还未绑定登录，是否现在去绑定？',
        confirm: true,
        original: false,
        type: "getUserInfo",
        fun: function (a, b) {
          console.log(b);
          if (b != undefined) {
            wx.setStorageSync("userInfo", b);
          } else {
            wx.hideLoading();
            njzxw.alert({
              msg: '无法获取您的信息，请至用户中心重新点击注册'
            });
            return;
          }

          wx.navigateTo({
            url: '/pages/reg/reg',
          })
        }
      });
    }
  },
  /**
   * 公共表单提交方法
   */
  addSubmit: function (opt) {

    opt.page['submit'] = function (e) {
      opt.page.setData({
        submitDisabled: true
      });
      var data = e.detail.value;
      //校验参数
      if (typeof opt.verify == 'function') {
        data = opt.verify(data);
      }
      if (typeof data == 'string') {
        njzxw.alert({
          msg: data
        });
        opt.page.setData({
          submitDisabled: false
        });
        return;
      }
      //进行提交
      if (data != null) {
        if(opt.checkUser == true){
          njzxw.checkUserInfo(opt.page, function () {
            njzxw.submit_(opt, data);
          })
        }else{
          njzxw.submit_(opt, data);
        }
      }
    }
  },
  submit_: function (opt, data){
    njzxw.alert({
      msg: '确定提交吗？',
      confirm: true,
      fun: function (a) {
        if (a) {
          njzxw.ajax({
            url: opt.url,
            data: data,
            load: true,
            loadTitle: '提交中',
            fun: function (a, b) {
              wx.hideLoading();
              if (a) {
                if (b.data.state == 1) {
                  njzxw.alert({
                    msg: b.data.msg,
                    fun: function () {
                      console.log("成功");
                      if (typeof opt.fun == 'function') {
                        opt.fun(true, b.data);
                      }
                      wx.navigateBack({
                        delta: 1
                      });
                    }
                  });
                } else {
                  njzxw.alert({
                    msg: b.data.msg
                  });
                }
              } else {
                console.log('????????????');
                njzxw.alert({
                  msg: '操作失败'
                });
              }
              opt.page.setData({
                submitDisabled: false
              });
            }
          });
        } else {
          // njzxw.alert({
          //   msg: '操作失败'
          // });
          opt.page.setData({
            submitDisabled: false
          });
        }
      }
    });
  },
  verify: function (e) {
    var val = e.detail.value;

  },
  alert: function (opt) {
    var def = {
      page: null,
      type: '',//open-type的能力 表示带有获取用户信息的按钮，否则是普通按钮
      btn: ['取消', '确定'],
      msg: '',
      title: '系统提示',
      original: true,
      confirm: false,
      fun: function (a, b) {

      }
    }
    njzxw.extend(def, opt);

    if (def.original == true) {//原生
      wx.showModal({
        title: def.title,
        showCancel: def.confirm,
        cancelText: def.btn[0],
        confirmText: def.btn[1],
        content: def.msg,
        success: function (res) {
          if (res.confirm) {
            def.fun(true);
          } else {
            def.fun(false);
          }
        }
      });
      return;
    }

    //判断相应条件是否存在
    opt.page.setData({
      alert_: {
        btn_s: def.btn[1],
        btn_e: def.btn[0],
        type: def.type,
        msg: def.msg,
        show: false,
        title: def.title
      }
    });
    opt.page['alertQuex'] = function () {
      opt.page.setData({
        alert_: {
          show: true
        }
      });
    }
    opt.page['alertQued'] = function (res) {
      console.log(res);
      opt.page.setData({
        alert_: {
          show: true
        }
      });
      if (njzxw.isEmpty(def.type)) {
        def.fun(true);
      } else {
        if (res.type != 'tap') {
          wx.showLoading({
            mask: true,
            title: '加载中'
          });
          def.fun(true, res.detail.userInfo);
        }
      }
    }
  },
  /**
   * dateTimeStamp 为时间如：2018-10-12 22:22:22
   */
  timeago_: function (date){
    if (njzxw.isEmpty(date)){
      return "无";
    }
    date = date.substring(0, 19);
    date = date.replace(/-/g, '/');
    var dateTimeStamp = new Date(date).getTime();
    return njzxw.timeago(dateTimeStamp);
  },
  /**
   * dateTimeStamp dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
   */
  timeago: function (dateTimeStamp){
    var result = '';
    var minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
    var hour = minute * 60;
    var day = hour * 24;
    var week = day * 7;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();   //获取当前时间毫秒
    console.log(now)
    var diffValue = now - dateTimeStamp;//时间差

    if (diffValue < 0) {
      return;
    }
    var minC = diffValue / minute;  //计算时间差的分，时，天，周，月
    var hourC = diffValue / hour;
    var dayC = diffValue / day;
    var weekC = diffValue / week;
    var monthC = diffValue / month;
    if (monthC >= 1 && monthC <= 3) {
      result = " " + parseInt(monthC) + "月前"
    } else if (weekC >= 1 && weekC <= 3) {
      result = " " + parseInt(weekC) + "周前"
    } else if (dayC >= 1 && dayC <= 6) {
      result = " " + parseInt(dayC) + "天前"
    } else if (hourC >= 1 && hourC <= 23) {
      result = " " + parseInt(hourC) + "小时前"
    } else if (minC >= 1 && minC <= 59) {
      result = " " + parseInt(minC) + "分钟前"
    } else if (diffValue >= 0 && diffValue <= minute) {
      result = "刚刚"
    } else {
      var datetime = new Date();
      datetime.setTime(dateTimeStamp);
      var Nyear = datetime.getFullYear();
      var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
      var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
      var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
      var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
      var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
      result = Nyear + "-" + Nmonth + "-" + Ndate
    }
    return result;
  }
}
module.exports = njzxw;
